package com.audaque.springboot.foshanupload.core.util.encode;


import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class Sha256Utils {
    public static final String SHA256 = "SHA-256";

    public Sha256Utils() {
    }

    public static byte[] sha256(byte[] input) {
        return digest(input, "SHA-256", (byte[])null, 1);
    }

    public static byte[] sha256(byte[] input, byte[] salt) {
        return digest(input, "SHA-256", salt, 1);
    }

    public static byte[] sha256(byte[] input, byte[] salt, int iterations) {
        return digest(input, "SHA-256", salt, iterations);
    }

    /**
     *
     * @param input
     * @param algorithm  查看https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#AlgorithmParameters
     * @param salt
     * @param iterations
     * @return
     */
    public static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for(int i = 1; i < iterations; ++i) {
                digest.reset();
                result = digest.digest(result);
            }

            return result;
        } catch (GeneralSecurityException var7) {
            throw new RuntimeException(var7);
        }
    }

    public static byte[] sha256(InputStream input) {
        return digest(input, "SHA-256");
    }

    private static byte[] digest(InputStream input, String algorithm) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            int bufferLength = 8192;
            byte[] buffer = new byte[bufferLength];

            for(int read = input.read(buffer, 0, bufferLength); read > -1; read = input.read(buffer, 0, bufferLength)) {
                messageDigest.update(buffer, 0, read);
            }

            return messageDigest.digest();
        } catch (Exception var6) {
            throw new RuntimeException(var6);
        }
    }
}
